package models.merchant;

import models.BaseModel;
import models.merchant.enums.AccountType;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;

import javax.persistence.*;
import java.util.List;
import java.util.Map;

/**
 * 资金流水记录
 * Created by buhaoba on 16/6/16.
 */
@Entity
@Table(name = "merchant_accounts")
public class MerchantAccount extends BaseModel {

    public static final String CACHE_MERCHANT_LINKId = "ULC_CACHE_MERCHANT_LINKID_";


    /**
     * 商户
     */
    @JoinColumn(name = "merchant_id")
    @ManyToOne
    public Merchant merchant;

    /**
     * 金额
     */
    @Column(name = "account")
    public Double account;

    /**
     * 账户余额
     */
    @Column(name = "account_balance")
    public Double accountBalance;

    //来源
    @Column( name = "source")
    public String source;


    /**
     * 资金流水类型
     * ORDER:订单费用入账 , 金额为正
     * TAKE_NOW:提现,金额为负
     */
    @Column(name = "account_type")
    @Enumerated(EnumType.STRING)
    public AccountType accountType;


    /**
     * json解析数据解析的较多并且出现问题,所以使用原生语句查询,避免过多的解析数据
     * @param merchantId
     * @param beganDate
     * @param endDate
     * @return
     */
    public static List<Map<String , Object>> loadByMerchantAndCreateAt(long merchantId , String beganDate , String endDate){
        String sqlSelect = "select a.id , a.account_type , a.account, date_format(a.create_at,'%Y-%m-%d %H:%m:%s') as create_at from merchant_accounts a where a.merchant_id = "+merchantId+" and a.create_at >= '"+beganDate+"' and a.create_at < '"+endDate+"'";

        Query query = MerchantAccount.em().createNativeQuery(sqlSelect);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        return query.getResultList();
    }


}
